package com.example.myapplication

import android.graphics.Color
import android.os.Bundle
import android.os.Looper
import android.text.method.PasswordTransformationMethod
import android.util.Log
import android.view.Gravity
import android.widget.EditText
import android.widget.LinearLayout.HORIZONTAL
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_pay.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.json.JSONArray
import java.lang.Exception
import java.lang.StringBuilder
import java.net.URLEncoder
import kotlin.concurrent.thread


class LoginActivity : AppCompatActivity() {

    val sever_ip = "192.168.43.8"
    //val userLogin_jsp = "http://${sever_ip}:8080/JspForAndroid/userLogin.jsp"
    val userLogin_jsp = "http://${sever_ip}:8080/JspForAndroid/userLogin.jsp"
    var return_loginInfo = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LoginUi().setContentView(this@LoginActivity)
    }

    lateinit var et_account: EditText
    lateinit var et_password: EditText

    inner class LoginUi : AnkoComponent<LoginActivity> {
        override fun createView(ui: AnkoContext<LoginActivity>) = with(ui) {
            verticalLayout {
                backgroundColor = context.resources.getColor(android.R.color.white)
                gravity = Gravity.CENTER_HORIZONTAL
                imageView(R.drawable.head).lparams {
                    width = dip(100)
                    height = dip(100)
                    topMargin = dip(64)
                }

                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL
                    orientation = HORIZONTAL
                    backgroundResource = R.drawable.bg_frame_corner
                    imageView {
                        image = resources.getDrawable(R.drawable.ic_username)
                    }.lparams(width = wrapContent, height = wrapContent) {
                        leftMargin = dip(12)
                        rightMargin = dip(15)
                    }
                    et_account = editText {
                        hint = "登录账户"
                        hintTextColor = Color.parseColor("#666666")
                        setText("张三")
                        textSize = 14f
                        background = null
                    }.lparams {
                        topMargin = dip(5)
                    }
                }.lparams(width = dip(300), height = dip(40)) {
                    topMargin = dip(30)
                }

                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL
                    orientation = HORIZONTAL
                    backgroundResource = R.drawable.bg_frame_corner
                    imageView {
                        image = resources.getDrawable(R.drawable.ic_password)
                    }.lparams(width = wrapContent, height = wrapContent) {
                        leftMargin = dip(12)
                        rightMargin = dip(15)
                    }
                    et_password = editText {
                        hint = "账户密码"
                        setTransformationMethod(PasswordTransformationMethod.getInstance())
                        hintTextColor = Color.parseColor("#666666")
                        textSize = 14f
                        background = null
                    }.lparams {
                        topMargin = dip(5)
                    }
                }.lparams {
                    width = dip(300)
                    height = dip(40)
                    topMargin = dip(10)
                }

                button("登录") {
                    gravity = Gravity.CENTER
                    background = resources.getDrawable(R.drawable.bg_login_btn)
                    textColor = Color.parseColor("#ffffff")
                    textSize = 18f
                    onClick {
                        if (et_account.text.toString().isNotEmpty() && et_password.text.toString().isNotEmpty()) {
                            getAllTrainInfoJson()


                            android.util.Log.d("213",return_loginInfo)
                           // toast("${return_loginInfo}")
//                            if (return_loginInfo.equals("false")){
//                                android.util.Log.d("213",return_loginInfo)
//                                toast("账户名或密码输入错误")
//                            }
//                            else{
                                startActivity<MainActivity>()
                                toast("登录成功")

                           // }
                        } else {
                            toast("请输入账户或者密码")
                        }
                    }
                }.lparams(width = dip(300), height = dip(44)) {
                    topMargin = dip(18)
                }

                linearLayout {
                    orientation = HORIZONTAL
                    gravity = Gravity.CENTER_VERTICAL
                    checkBox("记住密码") {
                        textColor = Color.parseColor("#666666")
                        textSize = 16f
                        leftPadding = dip(5)
                    }
                    textView("新用户注册") {
                        textColor = Color.parseColor("#1783e3")
                        gravity = Gravity.RIGHT
                        textSize = 16f
                        onClick {
                            startActivity<RegisterActivity>()
                        }
                    }.lparams(width = matchParent)
                }.lparams(width = dip(300)) {
                    topMargin = dip(18)
                }

                textView("Copyright © " + resources.getString(R.string.app_name)) {
                    textSize = 14f
                    gravity = Gravity.CENTER or Gravity.BOTTOM

                }.lparams {
                    bottomMargin = dip(35)
                    weight = 1f
                }
            }
        }
    }

    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                val requestBody = FormBody.Builder()
                    .add("user_name", URLEncoder.encode(et_account.text.toString(),"UTF-8"))
                    .add("user_password", URLEncoder.encode(et_password.text.toString(),"UTF-8"))
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(userLogin_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
                val result = parseJson(responseData)
                if (responseData != null){
                    runOnUiThread{
                        //txtData.text = result
                        //更新布
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    private fun parseJson(jsonData:String?):String{
        val builder = StringBuilder()

        try {
            //json数组
            val jsonArray = JSONArray(jsonData)
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val temp = jsonObject.getString("return_loginInfo")

                // builder.append("$movie_src--$movie_name--$movie_type--$movie_time--$movie_test--$movie_acter, ")
                return_loginInfo = temp
                Looper.prepare()
                Log.d("ttt2t:", "${return_loginInfo}")
                Looper.loop()
            }


        }catch (e: java.lang.Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }
}